<?php

namespace App\Http\Controllers\Frontend\Apply;

use App\Http\Controllers\Controller;
use App\Http\Repositories\Relation\UserObjectRepo;
use App\Http\Requests\Validators\Frontend\Apply\ApplyValidator;
use App\Traits\HelpFunctions;
use Illuminate\Http\Request;

/**
 * 申请相关
 */
class UserObjectController extends Controller
{
    use HelpFunctions;

    const VALIDATOR = ApplyValidator::class;

    public function __construct()
    {
        $this->self_repo = new UserObjectRepo;
    }

    public function show($id)
    {
        return $this->returnResponse($this->self_repo->getOneById($id));
    }

    /**
     * 用户申请的服务/需求列表
     */
    public function originSearch(Request $request)
    {
        //参数验证
        $args = $request->only(
            'type',
        );

        $this->my_validate($args, 'searchRules');
        $args["origin_user_id"] = $this->getUserId();

        return $this->returnResponse($this->self_repo->search($args, $args["type"]));
    }

    /**
     * 用户被申请的服务/需求列表
     */
    public function targetSearch(Request $request)
    {
        //参数验证
        $args = $request->only(
            'type',
        );

        $this->my_validate($args, 'searchRules');
        $args["target_user_id"] = $this->getUserId();

        return $this->self_repo->search($args, $args["type"]);
    }

    /**
     * 请求写入
     */
    public function store(Request $request)
    {
        //参数验证
        $args = $request->only(
            'type',
            'object_id',
        );

        $this->my_validate($args, 'storeRules');

        $args['origin_user_id'] = $this->getUserId();

        //检查该操作是否满足条件
        $args["target_user_id"] = $this->self_repo->check($args);

        if ($args["target_user_id"] == $args["origin_user_id"]) abort(422, "不能申请自己的服务/需求");

        //检查是否已经加入
        if (!empty($this->self_repo->getOneByConditions([
            ["type", "=", $args["type"]],
            ["origin_user_id", "=", $args["origin_user_id"]],
            ["object_id", "=", $args["object_id"]],
        ]))) {
            abort(422, "已经申请，请勿重复操作");
        }

        //添加数据
        return $this->returnResponse($this->self_repo->createOne($args));
    }

    public function delete($id)
    {
        return $this->self_repo->deleteById($id);
    }
}
